package com.dfiov.cloud.msmtools.config;

import com.dfiov.cloud.msmtools.enums.ResponseEnum;
import com.dfiov.cloud.msmtools.utils.ResponseUtils;
import com.pateo.qingcloud.framework.common.base.BaseRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseRestResponse<?> handleValidationException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        Map<String, String> errorMap = new LinkedHashMap<>(8);
        errors.forEach(error ->
                errorMap.put(error.getField(), error.getDefaultMessage())
        );

        return ResponseUtils.fail(ResponseEnum.SYSTEM_ERROR, errorMap);
    }

    // 处理未捕获的异常
    @ExceptionHandler(Exception.class)
    public BaseRestResponse<?> handleAllException(Exception e) {
        log.error("系统异常: ", e);
        return ResponseUtils.fail(ResponseEnum.SYSTEM_ERROR);
    }

}
